<template>
	<view class="uni-padding-wrap">
		
		<uni-section title="" type="line">
			<uni-card title="天气" >
				<text class="uni-body">
					{{location}}现在的气温为{{tq.temperature}}摄氏度，{{tq.text}}
					
					<uni-icons type="reload"  size="30" @click="ipdw()"/>
					
				</text>
			</uni-card>
		</uni-section>
		
		<uni-collapse>
			<uni-collapse-item  :open="collapseitemopen" :disabled="collapseitemdisable" id="collapse" ref="collapse">
				<template v-slot:title>
					<uni-search-bar @confirm="search" :focus="false" v-model="checkForm.name" @cancel="handle" >
					</uni-search-bar>
				</template>
				
				<uni-list>
					<uni-list-chat v-for="item in checkListMusic" :avatar-circle="true" title="uni-app" 
						:avatar="item.picurl" 
						:note="item.name +':'+item.artistsname" 
						:time="item.duration"
						 @click="playMusic(item)" :clickable="isClickable">
					</uni-list-chat>
				</uni-list>
				
			</uni-collapse-item>
		</uni-collapse>
		
		
		<uni-section title="音乐类型" type="line">
		  <uni-data-select
			v-model="type"
			:localdata="types"
			:clear="false"
			>
		  </uni-data-select>
		</uni-section>
			  
		<view class="uni-center" style="background:#FFFFFF; font-size:0;align-self: center;" >
			<image class="image" mode="widthFix" :src="picurl" />
		</view>	
		<view style="align-self: center;">
			{{artistsname}}:{{name}}
		</view>
		<view style="align-self: center;">
			{{formatTime(currentTime)}}&nbsp;&nbsp;/&nbsp;&nbsp;{{formatTime(duration)}}
		</view>
		<!-- 倒计时 -->
		<!-- <view style="align-self: center;">
			<uni-countdown style="align-self: center;" :show-day="false" :second="duration" @timeup="timeup" :start="start"/>
		</view> -->
			
		
		<!-- 进度条 -->
		<view class="uni-common-mt">
			<slider block-size="12" :value="position" :min="0" :max="duration" @changing="onchanging" @change="onchange"></slider>
		</view>
		
		<span style="align-self: center;">
			<view style="float: left;margin-right: 3rem;">
				<uni-icons type="headphones"  size="30" @click="initMusic()"/>
				<text class="uni-mt-5 uni-subtitle" style="align-self: center;">随机</text>
			</view>
			<!-- <view  style="float: left;margin-right: 3rem;">
				<image  class="icon-play" :src="playImage" @click="play"></image>
				<text class="uni-mt-5 uni-subtitle" style="align-self: center;">随机</text>
			</view> -->
			<view style="float: left;margin-right: 3rem;" @click="play">
				<uni-icons type="sound" :color="isPlaying ?'#007aff':'#5e6d82'" size="30" />
				<text :style="{color:isPlaying ?'#007aff':'#5e6d82'}" class="uni-mt-5 uni-subtitle">{{ isPlaying ? '播放' : '暂停'}}</text>
			</view>
			<view style="float: left;margin-right: 3rem;" @click="collectMusic">
				<uni-icons type="star-filled" :color="collectStatus ?'#007aff':'#5e6d82'" size="30" />
				<text :style="{color:collectStatus ?'#007aff':'#5e6d82'}" class="uni-mt-5 uni-subtitle">收藏</text>
			</view>
			<view style="float: left;margin-right: 3rem;" @click="mine">
				<uni-icons type="list" :color="mineStatus ?'#007aff':'#5e6d82'" size="30" />
				<text :style="{color:mineStatus ?'#007aff':'#5e6d82'}" class="uni-mt-5 uni-subtitle">我的</text>
			</view>
			<view style="float: left">
				<uni-icons type="download" :color="saveStatus ?'#007aff':'#5e6d82'" size="30" @click="downLoad()"/>
				<text :style="{color:saveStatus ?'#007aff':'#5e6d82'}" class="uni-mt-5 uni-subtitle" style="align-self: center;">下载</text>
			</view>
			
		</span>
		

		
		
		
		<!-- 播放与暂停的图片 -->
		<!-- <view class="play-button-area">
			<image class="icon-play" :src="playImage" @click="play"></image>
		</view> -->
	</view>
</template>
<script>
	import { sjMusic,addSjMusic,statusMusic, collectSjMusic, sjZjMusic ,checkMusic,ipdw,sstq} from '@/common/api.js'
	export default {
		data() {
			return {
				isClickable : true,
				collapseitemopen : false,
				collapseitemdisable : true,
				checkListMusic : [],
				
				title: "随机音乐",
				isPlaying: false,
				isPlayEnd: false,
				start : false,
				
				currentTime: 0,//改变，进度条改变
				duration: 0,
				
				url : '',
				picurl: '/static/music.jpeg',
				artistsname : '作者',
				name : '音乐',
				
				
				
				type: '热歌榜',//随机音乐类型
				types: [{ value: '热歌榜', text: "热歌榜" },
					  { value: '新歌榜', text: "新歌榜" },
					  { value: '飙升榜', text: "飙升榜" },
					  { value: '抖音榜', text: "抖音榜" },
					  { value: '电音榜', text: "电音榜" },],
					  
				isFirst: true,
				activeIndex : false,
				
				playType : "sj", //sj   mine
				
				addForm : {},
				
				checkForm : {
					name : ""
				},
				
				collectStatus : false,
				saveStatus : false,
				mineStatus : false,
				
				location : '',
				tq:{},
			}
		},
		computed: {
			position() {
				return this.isPlayEnd ? 0 : this.currentTime;
			},
			playImage() {
				return this.isPlaying ? "/static/pause.png" : "/static/play.png"
			}
		},
		
		onLoad() {
			//console.log("随机音乐onLoad")
			
			this.createAudio();
			this.sjMusic()
		},
		
		onUnload() {
			//console.log("随机音乐onUnload")
			if (this._audioContext != null && this.isPlaying) {
				this.stop();
			}
		},
		
		created() {
			this.ipdw();
		},
		
		onShow() {
			console.log("sjmusic","onshow")
		},
		methods: {
			playMusic(event){
				console.log("点击了playMusic")
				console.log(event)
				if(this.isFirst){
					this._isChanging = false;
					this._audioContext = null;
					this.createAudio();
					this.isFirst = false;
				}
				this._audioContext.src = event.url
				this.url = event.url;
				this.picurl = event.picurl;
				this.name = event.name;
				this.artistsname = event.artistsname;
				
				
				console.log(this.$refs.collapse)
				//this.collapseitemopen = false;
				//document.getElementById("collapse").click()
				
			},
			handle(){
				console.log("取消")
				this.collapseitemopen = false;
				this.collapseitemdisable = true;
				this.checkForm.name = '';
			},
			
			//回车进行搜索
			search(res) {
				this.collapseitemdisable=false;
				this.collapseitemopen=true;
				checkMusic(this.checkForm).then(res =>{
					console.log(res)
					this.checkListMusic = res.obj;
					
				})
				
				/* uni.showToast({
					title: '搜索：' + res.value,
					icon: 'none'
				}) */
			},
			
			ipdw() {
				//console.log("ipdw开始")
				ipdw().then(res=>{
					console.log(res)
					this.location = res.info.city;
					this.sstq(this.location)
				})
			},
			
			sstq(location) {
				
				sstq(location).then(res=>{
					//console.log(res)
					this.tq = res. results[0].now;
				})
			},
			
			mine(){
				if(this.isFirst){
					this._isChanging = false;
					this._audioContext = null;
					this.createAudio();
					this.isFirst = false;
				}
				if(this.playType === 'sj'){
					//console.log("播放我收藏的")
					this.playType = "mine";
					this.mineStatus = true;
				}else{
					//console.log("播放我收藏的")
					this.playType = "sj";
					this.mineStatus = false;
				}
				this.sjMusic();
			},
			collectMusic(){
				if(this.collectStatus){
					return 
				}
				console.log("点击了收藏")
				collectSjMusic(this.addForm).then(res =>{
					console.log(res)
					uni.showToast({
						title: res.message
					})
					this.collectStatus=true;
				})
			},
			formatTime(seconds) {
			  // 计算分钟数
			  const minutes = Math.floor(seconds / 60);
			  // 计算剩余的秒数
			  const remainingSeconds = (seconds % 60).toFixed(0); // 保留两位小数
			  return `${minutes} : ${remainingSeconds}`;
			},
			
			/* timeup(){
				console.log("倒计时结束")
			}, */
			downLoad(){
				if(this.saveStatus){
					return
				}
				//console.log("下载音乐")
				this.addMusic();
			},
			initMusic(){
				if(this.isFirst){
					this._isChanging = false;
					this._audioContext = null;
					this.createAudio();
					this.isFirst = false;
				}
				this.sjMusic();
				//this.isPlaying=true;
			},
			createAudio() {
				
				//创建并返回内部 audio 上下文 innerAudioContext 对象。
				var innerAudioContext = this._audioContext = uni.createInnerAudioContext();
				
				innerAudioContext.autoplay = true;
				//innerAudioContext.src = audioUrl;
				
				innerAudioContext.onPlay(() => {
					console.log('开始播放');
					this.addForm.url = this.url;
					this.addForm.picurl = this.picurl;
					this.addForm.name = this.name;
					this.addForm.artistsname = this.artistsname;
					this.addForm.type = this.type;
					this.isPlaying = true;
					this.statusMusic();
					//判断时间是否大于2分钟，如果大于2分钟就保存
					//获取状态， 是否保存，是否收藏
					if(innerAudioContext.duration>120){
						this.addMusic()
					}
				});
				
				innerAudioContext.onTimeUpdate((e) => {
					if (this._isChanging === true) {
						//console.log('时间更新');
						return;
					}
					/* console.log(innerAudioContext.currentTime ,innerAudioContext.duration) */
					this.currentTime = innerAudioContext.currentTime || 0;
					this.duration = innerAudioContext.duration || 0;
				});
				innerAudioContext.onEnded(() => {
					//console.log('播放结束');
					this.currentTime = 0;
					this.isPlaying = false;
					this.isPlayEnd = true;
					this.sjMusic();
				});
				innerAudioContext.onError((res) => {
					//console.log('播放错误');
					this.isPlaying = false;
					/* console.log(res.errMsg);
					console.log(res.errCode); */
				});
				return innerAudioContext;
			},
			
			onchanging() {
				/* console.log("进度条变化中") */
				this._isChanging = true;
			},
			
			onchange(e) {
				/* console.log("进度条变化")
				console.log(e.detail.value);
				console.log(typeof e.detail.value); */
				this._audioContext.seek(e.detail.value);
				this._isChanging = false;
			},
			play() {
				//this.sjMusic()
				if (this.isPlaying) {
					this.pause();
					return;
				}
				this.isPlaying = true;
				this._audioContext.play();
				this.isPlayEnd = false;
			},
			pause() {
				this._audioContext.pause();
				this.isPlaying = false;
			},
			stop() {
				this._audioContext.stop();
				this.isPlaying = false;
			},
			sjMusic() {
				if(this.playType === 'sj'){
					sjMusic(this.type).then(res => {
						/* console.log("获取到随机音乐",res)
						console.log("this._audioContext",this._audioContext) */
						this._audioContext.src = res.data.url
						this.url = res.data.url;
						this.picurl = res.data.picurl;
						this.name = res.data.name;
						this.artistsname = res.data.artistsname;
						
						this.collect = {};
						
					})
				}else{
					sjZjMusic().then(res=>{
						/* console.log("获取到随机音乐",res)
						console.log("this._audioContext",this._audioContext) */
						this._audioContext.src = res.obj.url
						this.url = res.obj.url;
						this.picurl = res.obj.picurl;
						this.name = res.obj.name;
						this.artistsname = res.obj.artistsname;
						this.collect = {};
					})
				}
				
			},
			addMusic(){
				var _this = this;
				addSjMusic(this.addForm).then(res =>{
					if(res.message === '保存成功'){
						this.saveStatus = true;
					}
					console.log(res)
					/* uni.showToast({
						title: res.message
					}) */
				})
			},
			statusMusic() {
				statusMusic(this.addForm).then(res => {
					if(res.collect === '已收藏'){
						this.collectStatus = true;
					}else {
						this.collectStatus = false;
					}
					if(res.save === '已保存'){
						this.saveStatus = true;
					}else {
						this.saveStatus = false;
					}
					
				})
			}
			
		}
	}
</script>
<style>
	.play-time-area {
		display: flex;
		flex-direction: row;
		margin-top: 20px;
	}

	.duration {
		margin-left: auto;
	}

	.play-button-area {
		display: flex;
		flex-direction: row;
		justify-content: center;
		margin-top: 50px;
	}

	.icon-play {
		width: 30px;
		height: 30px;
	}
	
	.image {
		margin:40rpx 0;
		width: 400rpx;
		
	}
</style>
